﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Microsoft.Phone.Controls;

namespace ToyundaPhone.Pages
{
	public partial class PlaylistPage : PhoneApplicationPage, System.ComponentModel.INotifyPropertyChanged
	{
		public PlaylistPage()
		{
			InitializeComponent();
		}

		#region INotifyPropertyChanged Members

		public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

		#endregion

		public Database.Playlist Playlist { get; private set; }
		public IEnumerable<Database.Song> Songs { get; private set; }

		private void OnPropertyChanged(string propertyName)
		{
			if (PropertyChanged != null)
			{
				PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
			}
		}

		private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
		{
			string IdParam = NavigationContext.QueryString["playlist"];
			int id;
			if (!int.TryParse(IdParam, out id))
			{
				NavigationService.GoBack();
				return;
			}
			Database.SongDatabase db = (Application.Current as App).SongDatabase;
			Database.Playlist pl = (from p in db.Playlists where p.Id == id select p).FirstOrDefault();
			if (pl == null)
			{
				NavigationService.GoBack();
				return;
			}
			Playlist = pl;
			Songs = from s in db.Songs join ps in db.PlaylistSongs on s.Id equals ps.Song where ps.Playlist == pl.Id select s;
			OnPropertyChanged("Playlist");
			OnPropertyChanged("Songs");
		}

		private void SongList_ListUpdated(object sender, EventArgs e)
		{
			var tmp = Songs;
			Songs = null;
			OnPropertyChanged("Songs");
			Songs = tmp;
			OnPropertyChanged("Songs");
		}

		private void Add_Click(object sender, EventArgs e)
		{
			NavigationService.Navigate(new Uri(string.Format("/songsearch/{0}", Playlist.Id), UriKind.Relative));
		}

		private void Empty_Click(object sender, EventArgs e)
		{
			if (MessageBox.Show("Êtes-vous sûr de vouloir supprimer cette liste ?", Playlist.Name, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
			{
				Database.SongDatabase db = (Application.Current as App).SongDatabase;
				db.PlaylistSongs.DeleteAllOnSubmit(Playlist.PlaylistSongs);
				db.SubmitChanges();
				var tmp = Songs;
				Songs = null;
				OnPropertyChanged("Songs");
				Songs = tmp;
				OnPropertyChanged("Songs");
			}
		}

		private void PhoneApplicationPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
		{
			Microsoft.Phone.Shell.SystemTray.SetIsVisible(this, e.Orientation == PageOrientation.Portrait || e.Orientation == PageOrientation.PortraitUp || e.Orientation == PageOrientation.PortraitDown);
		}
	}
}